package com.golddaymicromall.activity.leavemsg;

import android.content.Intent;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.adapter.LeaveMsggAdapter;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.LeaveMsgInfo;
import com.golddaymicromall.module.ListViewLoadMore;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class LeaveMsgActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener, ListViewLoadMore.IsLoadingListener {
    private String customerid;
    private LeaveMsggAdapter adapter;
    private List<LeaveMsgInfo> list;
    private List<LeaveMsgInfo> listAll = new ArrayList<LeaveMsgInfo>();
    private ListViewLoadMore mlv;
    private Button NewAdd;
    private Handler handler = new Handler();
    int CurrentPageNum = 0;
    private LinearLayout mLeaveMsgBoard_Back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_leave_msg);
        initView();
        customerid = SPUtils.get(getApplicationContext(), "Id", "").toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        CurrentPageNum = 1;
        attemptLeaveMsg(CurrentPageNum);
    }

    private void initView() {
        mlv = (ListViewLoadMore) findViewById(R.id.leaveMsgLv);
        mlv.setOnItemClickListener(this);
        NewAdd = (Button) findViewById(R.id.NewAdd);
        mLeaveMsgBoard_Back = (LinearLayout) findViewById(R.id.leaveMsgBoard_back);
        mLeaveMsgBoard_Back.setOnClickListener(this);
        NewAdd.setOnClickListener(this);
        mlv.setOnLoadingListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> mlv, View arg1, int arg2, long arg3) {

    }

    private void attemptLeaveMsg(int CurrentPageNum) {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.message.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerid", customerid);
        form.put("current_pagenum", String.valueOf(CurrentPageNum));
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(LeaveMsgActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                        } else {
                            list = JSON.parseArray(result, LeaveMsgInfo.class);
                            if (CurrentPageNum > 1) {
                                listAll.addAll(list);
                            } else if (CurrentPageNum == 1) {
                                listAll.clear();
                                listAll.addAll(list);
                            }
                            Collections.sort(listAll, new Comparator<LeaveMsgInfo>() {
                                @Override
                                public int compare(LeaveMsgInfo lhs, LeaveMsgInfo rhs) {
                                    Date date1 = lhs.getMessagedate();
                                    Date date2 = rhs.getMessagedate();
                                    // 对日期字段进行升序，如果欲降序可采用after方法
                                    if (date1.before(date2)) {
                                        return 1;
                                    }
                                    return -1;
                                }
                            });
                            adapter = new LeaveMsggAdapter(listAll, LeaveMsgActivity.this);
                            mlv.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            if (CurrentPageNum > 1) {
                                mlv.setSelection(mlv.getCount() - 1);
                            }
                        }
                    } else {
                        Toast.makeText(LeaveMsgActivity.this, "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }

                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.NewAdd:
                Intent intent = new Intent(this, NewAddActivity.class);
                startActivity(intent);
                break;
            case R.id.leaveMsgBoard_back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoad() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CurrentPageNum++;
                attemptLeaveMsg(CurrentPageNum);

                adapter.notifyDataSetChanged();
                mlv.complateLoad();
            }
        }, 3000);


    }

    public String dateToString(Date ctime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            String date = formatter.format(ctime);
            return date;
        } catch (Exception e) {

        }
        return null;
    }
}
